import { interpreter } from "@/api/request";
import { delHisotryMesssage, getHisotryMesssageList } from "@/api/zixun";
import debounce, { debounceImmediate } from "@/utils/debounce";
import { ref } from "vue";
export interface HistoryItemProps {
  id: number;
  messages_id: string;
  user_id: number;
  rb_robot_id: number;
  question: string;
  msg?: any;
  created_at: string;
  rb_robot: {
    id: number;
    nickname: string;
    short_name: string;
  };
  last_msg: {
    id: number;
    question: string;
  };
}
export default function useHistoryMessage() {
  const record = ref<{
    page: number;
    showDel: boolean;
    list: Array<HistoryItemProps>;
  }>({
    page: 1,
    showDel: false,
    list: []
  });
  const historyPopup = ref<{ open?: () => void; close?: () => void }>();
  const getHisotryMessage = async () => {
    if (record.value.list.length) {
      return;
    }
    const [err, res] = await interpreter(getHisotryMesssageList(2));
    if (!err) {
      record.value.list = res;
    }
  };
  const delHistoryMessage = debounceImmediate(async (id, index: number) => {
    uni.showModal({
      title: "是否要删除该记录",
      async success(res) {
        if (res.confirm) {
          const [err] = await interpreter(delHisotryMesssage([id]));
          if (!err) {
            record.value.list.splice(index, 1);
            // if (record.value.list.length === 0) {
            //   hideHistory();
            // }
          }
        }
      }
    });
  });

  const triggleShowDel = () => {
    record.value.showDel = !record.value.showDel;
  };

  const showHistory = debounce(async (id: number) => {
    if (historyPopup.value) {
      await getHisotryMessage();
      historyPopup.value.open?.();
    }
  });
  const hideHistory = () => {
    if (historyPopup.value) {
      historyPopup.value.close?.();
    }
  };
  return {
    record,
    historyPopup,
    triggleShowDel,
    showHistory,
    hideHistory,
    getHisotryMessage,
    delHistoryMessage
  };
}
